﻿//
//jFileControl
//
(function ($) {
    $.fn.jFileControl = function (options) {
        //alert(this.attr('json_data'));
        var $this = this;

        var ranIndex = new Date().valueOf();
        if ($this.attr('init') != '1') {


        if ($this.attr('readonly') != 'True') {
            this.find('.toolBar').append('<li><a class="add" href="javascript:void(0)"><input id="upload' + ranIndex + '" class="uploadify" type="file"/></a></li>');
            this.find('.toolBar').append('<li><a class="delete" href="javascript:void(0)"><span>删除勾选</span></a></li>');
        }

        var queueid = 'uploadqueue' + ranIndex;
        this.append('<div id="' + queueid + '" class="uploadify-queue"></div>');

        var fileUploadComplete = function (event, response) {
            insertRow($.parseJSON(response).simple);
        }



        var options = {
            swf: '/SystemManage/javascripts/uploadify/uploadify.swf',
            uploader: '/SystemManage/Control/FileControl/Upload/Upload.aspx',
            queueID: queueid,
            height: 23,
            width: 50,
            buttonText: '添加',
            removeTimeout: 0.5,
            fileTypeDesc: this.attr("file_desc"),
            fileTypeExts: this.attr("file_filters"),
            fileObjName: this.attr("name") || "file",
            auto: this.attr("auto") || true,
            multi: false,
            formData: { User: this.attr('user'), ajax: 1, cfgjson: BASE64.encoder($this.attr('upload_config')) },
            onUploadError: uploadifyError,
            //onUploadComplete: fileUploadComplete,
            onUploadSuccess: fileUploadComplete

        };


        this.find('.uploadify').uploadify(options);

        }
        else {
            var $table = $this.find('table.list');
            $table.find('#grid_list').empty();
        }



        var groupIndex = 'group' + ranIndex;
        $this.find('table.list>thead>tr>th>input.checkboxCtrl').attr('group', groupIndex);


        $this.find('.toolBar>li:eq(1)').click(function () {
            alertMsg.confirm("确认要删除么?", {
                okCall: function () {
                    var $table = $this.find('table.list');
                    $table.find("tbody>tr>td>input:checked[name='" + groupIndex + "']").each(function () {
                        $table.find("tbody>tr[key='" + $(this).attr('value') + "']").remove();
                    });
                    updateValue();
                }
            });
        });

        var fileCount = 0;

        //插入行
        var insertRow = function (result) {
            if (fileCount >= $this.attr('file_cnt_limit')) {
                alertMsg.warn('最多只能保存' + $this.attr('file_cnt_limit') + '项纪录。');
                return;
            }
            if (result[$this.attr('key_col')]) {

                var $table = $this.find('table.list');

                var $row = $table.find('tr[key=' + result[$this.attr('key_col')] + ']');

                var i = result.FileName.lastIndexOf(".");
                var ext = "";
                var imgs = "jpg,jpeg,gif,png";
                if (i >= 0) {
                    ext = result.FileName.substring(i + 1);
                }

                var row = '<tr key="' + result[$this.attr('key_col')] + '">';
                row += '<td><input name="' + groupIndex + '" value="' + result[$this.attr('key_col')] + '" type="checkbox"/></td>';
                $table.find('thead>tr>th[prop]').each(function () {
                    row += '<td prop="' + $(this).attr('prop') + '" style="' + $(this).attr('style') + '">';
                    if ($(this).attr('prop') == 'FileName') {
                        row += "<div class=ext_" + ext + "><span style='margin-left:20px;line-height:16px;'>" + result.FileName + "</span></div>";
                    } else {
                        row += result[$(this).attr('prop')];
                    }
                    row += '</td>';
                });

                //操作
                row += "<td align=center>";
                if (i > 0 && imgs.indexOf(ext) >= 0) {
                    row += "<a href='" + result.FilePath + "' class='prettyPhoto' title='" + result.FileName + "'>预览</a>";
                }
                else {
                    row += "<a style='color: #C0C0C0'>预览</a>";
                }

                row += "&nbsp;&nbsp;<a href='/SystemManage/Basics/File/Download.aspx?uid=" + result.FileId + "'>下载</a>"

                if ($this.attr('readonly') != 'True') {
                    row += '&nbsp;&nbsp;<a del="1" href="javascript:void(0)">删除</a>';
                }
                row += "</td>";

                row += '</tr>';
                //                if ($row.length > 0) {
                //                    $row.before(row);
                //                    $row.remove();
                //                } else {
                //                    $table.find('tbody>tr:last').before(row);
                //                }
                $table.find('tbody').append(row);
                $table.find('tbody>tr').removeClass();
                $table.cssTable();

                $row = $table.find('tr[key=' + result[$this.attr('key_col')] + ']');
                $row.find('.prettyPhoto').prettyPhoto();
                $row.find('a[del]').click(function () {
                    alertMsg.confirm("确认要删除?", {
                        okCall: function () {
                            $row.remove();
                            updateValue();
                        }
                    });
                });
                updateValue();
            }
        }

        //更新json值
        var updateValue = function () {
            var $table = $this.find('table.list');
            var resultList = [];
            fileCount = 0;
            $table.find('tr[key]').each(function () {
                var $row = $(this);
                var obj = {};
                $table.find('thead>tr>th[prop]').each(function () {
                    obj[$(this).attr('prop')] = $row.find('td[prop="' + $(this).attr('prop') + '"]').text();
                });
                fileCount++;
                resultList.push(obj);
            });
            $this.find('.grid_json').val($.toJSON(resultList));
        }

        //插入初始值
        var initList = [];
        try {
            initList = $.parseJSON($this.attr('json_data'));
        } catch (e) { }
        $(initList).each(function () {
            insertRow(this);
        });

        $this.attr('init', '1');
    }


})(jQuery);
